﻿using BusinessEntity;
using BusinessRepository;
using learun.util;
using Newtonsoft.Json.Linq;
using System;
using System.Collections.Generic;
using System.Data;
using System.Text;
using System.Threading.Tasks;

namespace BusinessRule.Organization
{
    public class UserRule
    {
        #region 查询数据
        /// <summary>
        /// 获取用户信息
        /// </summary>
        /// <param name="keyValue">主键</param>
        /// <returns></returns>
        public static Task<AUserEntity> GetEntity(string keyValue)
        {
            //return userService.GetEntity(keyValue);
            return new RepositoryFactory().BaseRepository().FindEntityByKey<AUserEntity>(keyValue);
        }
        /// <summary>
        /// 获取登录者用户信息
        /// </summary>
        /// <returns></returns>
        public static async Task<AUserEntity> GetEntity()
        {
            string account = ContextHelper.GetItem("account") as string;
            if (string.IsNullOrEmpty(account))
            {
                return new AUserEntity();
            }
            return await GetEntityByAccount(account);
        }

        /// <summary>
        /// 获取用户信息通过账号
        /// </summary>
        /// <param name="account">用户账号</param>
        /// <returns></returns>
        public static Task<AUserEntity> GetEntityByAccount(string account)
        {
            string fieldSql = @" 
                        t.F_UserId,
                        t.F_EnCode,
                        t.F_Account,
                        t.F_Password,
                        t.F_Secretkey,
                        t.F_RealName,
                        t.F_NickName,
                        t.F_HeadIcon,
                        t.F_QuickQuery,
                        t.F_SimpleSpelling,
                        t.F_Gender,
                        t.F_Birthday,
                        t.F_Mobile,
                        t.F_Telephone,
                        t.F_Email,
                        t.F_OICQ,
                        t.F_WeChat,
                        t.F_MSN,
                        t.F_CompanyId,
                        t.F_DepartmentId,
                        t.F_SecurityLevel,
                        t.F_OpenId,
                        t.F_Question,
                        t.F_AnswerQuestion,
                        t.F_CheckOnLine,
                        t.F_AllowStartTime,
                        t.F_AllowEndTime,
                        t.F_LockStartDate,
                        t.F_LockEndDate,
                        t.F_SortCode,
                        t.F_DeleteMark,
                        t.F_EnabledMark,
                        t.F_Description,
                        t.F_CreateDate,
                        t.F_CreateUserId,
                        t.F_CreateUserName,
                        t.F_ModifyDate,
                        t.F_ModifyUserId,
                        t.F_ModifyUserName
                        ";

            fieldSql = "t.*";

            var strSql = new StringBuilder();
            strSql.Append("SELECT ");
            strSql.Append(fieldSql);
            strSql.Append(" FROM AUser t ");
            strSql.Append(" WHERE t.Account = @account   ");//AND t.F_DeleteMark = 0
            return new RepositoryFactory().BaseRepository().FindEntity<AUserEntity>(strSql.ToString(), new { account });
        }
        #endregion

        #region 扩展方法
        /// <summary>
        /// 判断密码是否正确
        /// </summary>
        /// <param name="oldPassword">旧密码</param>
        /// <param name="newPassWord">新密码</param>
        /// <param name="secretkey">密钥</param>
        /// <returns></returns>
        public static bool IsPasswordOk(string oldPassword, string newPassWord, string secretkey)
        {

            //string dbPassword = Md5Helper.Encrypt(DESEncrypt.Encrypt(newPassWord, secretkey).ToLower(), 32).ToLower();

            //if (dbPassword == oldPassword)
            //{
            //    return true;
            //}

            if (newPassWord == oldPassword)
            {
                return true;
            }

            return false;
        }

        //获取项目用户 depid
        public static async Task<string> GetUserDepid(string userid)
        {
            string str2 = "(";

            str2 += "'1369830999248211970'";
            //DataTable table = await TranstionRule.ProcessSql("select ksid from view_userinfos where userid ='" + userid + "'");
            //for (int i = 0; i < table.Rows.Count; i++)
            //{
            //    string[] strArray = table.Rows[i]["ksid"].ToString().Split(new char[] { ',' });
            //    for (int j = 0; j < strArray.Length; j++)
            //    {
            //        str2 = str2 + "'" + strArray[j].ToString() + "',";
            //    }
            //    str2 = str2.TrimEnd(new char[] { ',' });
            //}
            return (str2 + ")").Replace("()", "('')");
        }

        /// <summary>
        /// 从java接口获取用户部门
        /// </summary>
        /// <param name="userid"></param>
        /// <returns></returns>
        public static async Task<string> GetUserDepidBYUserID(string userid)
        {
            string depid = "";
            string json = "";

            string url = ConfigHelper.GetConfig().IMUrl + "/user/";
            string body = "id=" + userid;
            //json = HttpMethods.Get(url + "?" + body).GetAwaiter().GetResult();
            json = JavaApi.HttpPost(url, body);
            JObject jo = JObject.Parse(json);
            JObject jb = JObject.Parse(jo["data"].ToString());
            depid = "('"+jb["deptId"].ToString()+"')";
            return depid;
        }

        #endregion 
    }
}
